package com.peng.filter;

import com.alibaba.fastjson.JSON;
import com.peng.common.R;
import com.peng.utils.BaseContextUtils;
import com.sun.prism.impl.BaseContext;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    private static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response= (HttpServletResponse) servletResponse;

        String[] str=new String[]{
                "/employee/login",
                "/employee/logout",
                "/front/**",
                "/backend/**",
                "/user/sendMsg", //移动端发送短信
                "/user/login",  // 移动端登陆
                "/doc.html",     //swagger文档
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"

        };

        String requestURI = request.getRequestURI();

        boolean check = check(str, requestURI);

        if (check){
            filterChain.doFilter(request, response);
            return;
        }

        Long employeeId = (Long) request.getSession().getAttribute("employeeId");
        if (employeeId!=null){
            BaseContextUtils.setId(employeeId);
            filterChain.doFilter(request,response);
            return;
        }

        //4-2判断移动端登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("user") != null){
            //log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));
            //把用户id存储到本地的threadLocal
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContextUtils.setId(userId);


            filterChain.doFilter(request,response);
            return;
        }

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        if (requestURI.equals("/")){
            response.sendRedirect("/backend/page/login/login.html");
            return;
        }
        return;
    }

    public boolean check(String[] strings , String uri){
        for (String string : strings) {
            boolean match = PATH_MATCHER.match(string, uri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
